import { debounceTime } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { ChangeDetectorRef, Component, Input, OnInit, Output } from '@angular/core';
import { BaseService } from '@shared';
import { EventEmitter } from '@angular/core';
@Component({
  selector: 'app-rebate-table',
  templateUrl: './rebate-table.component.html',
  styleUrls: ['./rebate-table.component.less']
})
export class RebateTableComponent implements OnInit {
  @Input() data: any = [];     // 数据
  @Input() type: any;          // 配置类型 1全部等级 2不同等级
  @Input() hiden!: boolean;    // 判断新增/查看 
  @Output()
  private dataChange: EventEmitter<any> = new EventEmitter();
  emit() {
    this.dataChange.emit(this.data);
  }
  headers: any[] = [];
  gradeConfigId: string = '';
  grage: any[] = [];
  formatterDollar = (value: number): string => `${value}`;
  changeSub = new Subject<string>();
  constructor(public service: BaseService, private cdr: ChangeDetectorRef) {}

  ngOnInit(): void {
    if (this.type == '2') {
      this.loadData();
    }
    // 新增-不同等级情况
    if (!this.hiden && this.type == '2') {
      this.data = [
        {
          gradeConfigId: '',
          startAmount: 0,
          endAmount: 0,
          managementFeeRatio: 0,
        }
      ];
    // 新增-全部等级情况
    } else if (!this.hiden && this.type == '1'){
      this.data = [
        {
          gradeConfigId: '0',
          startAmount: 0,
          endAmount: 0,
          managementFeeRatio: 0,
        }
      ];
    }
    this.changeendAmountAction();
  }

  loadData() {
    this.service.request('/api/mdc/partnerGradeConfig/listPartnerGradeConfig').subscribe(res => {
      if (res) {
        this.grage = res;
        this.cdr.detectChanges();
      }
    });
  }

  /**
   * 修改结束公里数
   * @param event 车长
   * @param i 下标
   */
  changeendAmount(event: any, i: number) {
    if (event) {
      this.changeSub.next(`${event},${i}`);
    }
  }
  changeendAmountAction() {
    this.changeSub.pipe(debounceTime(500)).subscribe((res: string) => {
      if (res) {
        const paras = res.split(',');
        const num = Number(paras[0]);
        const i = Number(paras[1]);

        if (num <= this.data[i]?.startAmount) {
          this.data[i].endAmount = null;
          setTimeout(() => {
            this.data[i].endAmount = this.data[i]?.startAmount + 1;
          }, 0);
          this.changeNextstartAmount(this.data[i]?.startAmount + 1, i + 1);
          return;
        }
        this.data[i].endAmount = num;
        this.changeNextstartAmount(num, i + 1);
      }
    });
  }

  add() {
    const tem = this.data[this.data?.length - 1];
    if (tem) {
      this.data.push({
        gradeConfigId: '',
        startAmount: 0,
        endAmount: 0,
        managementFeeRatio: 0
      });
      this.data = [...this.data];
    }
  }

  deleteRow(index: number) {
    var newArr = this.data.concat();
    newArr.splice(this.data.length - 1, 1);
    // this.data = this.data.pop()
    this.data = [...newArr];
  }

  /**
   * 遍历同步后置位公里数
   * @param event  车长
   * @param i 下标
   */
  private changeNextstartAmount(event: number, i: number) {
    if (this.data[i]) {
      this.data[i].startAmount = event;
      if (this.data[i].endAmount <= event) {
        this.data[i].endAmount = this.data[i].startAmount + 1;
        this.changeNextstartAmount(event + 1, i + 1);
      }
    }
  }
}
